/*

� 最佳窗口参数结果：
� 最大准确率: windowSize = 194, 准确率 = 67.36%, 最大错连 = 8
�️ 最小错连: windowSize = 5, 准确率 = 65.35%, 最大错连 = 8

*/


// 📦 引入工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 📦 ESM 支持模块加载
const esm = require("esm");
const requireModule = esm(module);

// 📦 项目依赖模块
const { readAllValues } = requireModule(
  "../../../awakened-potential/helpers/readAllValues.js"
);
const checkAccuracy = requireModule("../../utils/checkAccuracy.js");

// ✅ 读取历史开奖数据（模拟全部）
const allValues = readAllValues("m");

// ✅ 号码池（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);

// ✅ 最近最大间隔策略函数
const recentMaxGapStrategy = (temp) => {
  const history = temp.map((item) => item.number);
  const lastIndexMap = new Map(); // 存储号码上次出现的索引
  const gaps = []; // 每个号码的最近间隔

  for (let i = history.length - 1; i >= 0; i--) {
    const num = history[i];
    if (lastIndexMap.has(num)) {
      const gap = lastIndexMap.get(num) - i;
      gaps.push({ number: num, gap });
      lastIndexMap.set(num, i);
    } else {
      lastIndexMap.set(num, i);
    }
  }

  const uniqueSorted = _.uniqBy(_.orderBy(gaps, "gap", "desc"), "number");

  const selected = uniqueSorted.slice(0, 32).map((item) => item.number);

  // 补足不足 32 个的情况
  const selectedSet = new Set(selected);
  for (const n of allNumbers) {
    if (selectedSet.size >= 32) break;
    if (!selectedSet.has(n)) selectedSet.add(n);
  }

  const result = Array.from(selectedSet);

  if (result.length !== 32) {
    throw new Error(`❗ 无法生成 32 个不重复号码（目前只有 ${result.length} 个）`);
  }

  return result;
};

// ✅ 记录所有窗口测试结果
const allStats = [];

for (let windowSize = 5; windowSize <= 200; windowSize++) {
  let correct = 0;
  let maxWrongStreak = 0;
  let currentWrongStreak = 0;
  const predictResults = [];

  allValues.forEach((item, index) => {
    const temp = allValues.slice(Math.max(0, index - windowSize), index);
    if (temp.length === 0) return;

    const selectedNumbers = recentMaxGapStrategy(temp);

    try {
      const isHit = checkAccuracy(selectedNumbers, item.number);
      if (isHit) {
        correct += 1;
        currentWrongStreak = 0;
      } else {
        currentWrongStreak += 1;
        maxWrongStreak = Math.max(maxWrongStreak, currentWrongStreak);
      }
      predictResults.push(selectedNumbers);
    } catch (err) {
      console.error(`❌ checkAccuracy error at index ${index}: ${err.message}`);
    }
  });

  const total = predictResults.length;
  const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : 0;

  allStats.push({
    windowSize,
    accuracy: Number(accuracy),
    maxWrongStreak,
  });

  console.log(
    `✅ windowSize=${windowSize}, 准确率=${accuracy}%, 最大连续错误=${maxWrongStreak}`
  );
}

// ✅ 找出最佳窗口参数
const bestAccuracy = _.maxBy(allStats, "accuracy");
const bestStable = _.minBy(allStats, "maxWrongStreak");

console.log("\n📊 最佳窗口参数结果：");
console.log(`🎯 最大准确率: windowSize = ${bestAccuracy.windowSize}, 准确率 = ${bestAccuracy.accuracy}%, 最大错连 = ${bestAccuracy.maxWrongStreak}`);
console.log(`🛡️ 最小错连: windowSize = ${bestStable.windowSize}, 准确率 = ${bestStable.accuracy}%, 最大错连 = ${bestStable.maxWrongStreak}`);
